package reduce.fz.com.reduce.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.TypeReference;

import java.io.UnsupportedEncodingException;
import java.util.List;

import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.abstracts.AbResponseListener;
import reduce.fz.com.reduce.activity.VideoCardDetailActivity;
import reduce.fz.com.reduce.adapter.BaseRecycleViewHolder;
import reduce.fz.com.reduce.bean.ServiceException;
import reduce.fz.com.reduce.bean.VideoCard;
import reduce.fz.com.reduce.bean.page.Pagination;
import reduce.fz.com.reduce.bean.result.Result;
import reduce.fz.com.reduce.custom.NetworkImageView;
import reduce.fz.com.reduce.custom.delegate.RecyclerViewDelegate;
import reduce.fz.com.reduce.custom.view.RoundNetworkImageView;
import reduce.fz.com.reduce.fragment.base.BaseListFragment;
import reduce.fz.com.reduce.util.ApiUtil;
import reduce.fz.com.reduce.util.HttpUtils;
import reduce.fz.com.reduce.util.ScreenUtils;

/**
 */
public class VideoCardListFragment extends BaseListFragment<VideoCardListFragment.VideoViewHolder, VideoCard> {
    private Long uid = null;
    //type=0根据tagid查询 type=1 根据关键字查询
    private int type = 0;
    private String keyword;
    private Long tagid;

    public static VideoCardListFragment createTag(Long tagid) {
        VideoCardListFragment fragment = new VideoCardListFragment();
        Bundle bundle = new Bundle();
        bundle.putLong("tagid", tagid);
        bundle.putInt("type", 0);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static VideoCardListFragment createSerach() {
        VideoCardListFragment fragment = new VideoCardListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", 1);
        fragment.setArguments(bundle);
        return fragment;
    }

    public void searchVideo(String info) {
        try {
            keyword = java.net.URLEncoder.encode(info, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        firstPage();
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getArguments().getInt("type", 0);
        tagid = getArguments().getLong("tagid", 0);

    }

    public VideoCardListFragment() {
    }

    @Override
    public void request(String url) {
        HttpUtils.get(url, new AbResponseListener<List<VideoCard>>(new TypeReference<Result<List<VideoCard>>>() {
        }) {
            @Override
            public void error(ServiceException e) {
                loadingDialog.dismiss();
                addResult(null);
            }

            @Override
            public void responseInfo(Result<List<VideoCard>> data) {
                addResult(data);
            }
        });
    }

    @Override
    public LinearLayoutManager getLayoutManager() {
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 3);
        return layoutManager;
    }

    /**
     * @param cardid
     */
    public void forwardDetail(Long cardid) {
        Intent intent = new Intent(this.getActivity(), VideoCardDetailActivity.class);
        intent.putExtra("cardid", cardid);
        startActivity(intent);
    }


    @Override
    public int getSpanSize() {
        return 3;
    }

    @Override
    protected VideoViewHolder createItemViewHolder(ViewGroup parent) {
        View view = layoutInflater.inflate(R.layout.view_search_video_item, parent, false);
        VideoViewHolder viewHolder = new VideoViewHolder(view, new DetailVideoListener() {
            @Override
            public void videoCardClick(VideoCard card) {
                forwardDetail(card.cardid);
            }
        });
        return viewHolder;
    }

    @Override
    protected VideoViewHolder createfootViewHolder(View view) {
        return new VideoViewHolder(view);
    }

    @Override
    protected String setUrlBeforeRequest(List<VideoCard> datas, Pagination pagination) {
        String url = getUrl(pagination);
        return url;
    }

    public String getUrl(Pagination pagination) {
        String url = "";
        switch (type) {

            case 0:
                url = ApiUtil.getApi(context, R.array.api_search_video_tag, tagid, pagination.getPageNo(), pagination.getPageSize());
                break;
            case 1:
                url = ApiUtil.getApi(context, R.array.api_search_video_keyword, pagination.getPageNo(), pagination.getPageSize());
                url=url+"&keyword="+keyword;
                break;
            default:
                url = "";
                break;

        }
        return url;
    }

    @Override
    protected int getPageType() {
        return 0;
    }

    public interface DetailVideoListener {
        public void videoCardClick(VideoCard card);

    }

    public static class VideoViewHolder extends BaseRecycleViewHolder<VideoCard> {
        //视频封面
        private NetworkImageView mVideoThum;
        //视频描述
        private TextView mVideoDesc;
        //点赞
        private TextView mZan;

        private RoundNetworkImageView mAvatar;

        private View itemView;

        private DetailVideoListener listener;
        private int margin;
        Boolean isFirstLine = false;
        Boolean isFristRow = false;
        Boolean isSecondRow = false;
        Boolean isThridRow = false;
        private RelativeLayout mRlThum;

        public VideoViewHolder(View itemView, DetailVideoListener listener) {
            this(itemView);
            margin = itemView.getResources().getDimensionPixelSize(R.dimen.dimen_3);
            this.listener = listener;
        }

        public void initWidget(View itemView) {
            this.itemView = itemView;
            mVideoThum = (NetworkImageView) itemView.findViewById(R.id.niv_video_thum);
            mVideoDesc = (TextView) itemView.findViewById(R.id.tv_video_desc);
            mZan = (TextView) itemView.findViewById(R.id.tv_zan);
            mAvatar = (RoundNetworkImageView) itemView.findViewById(R.id.iv_user_avatar);
            mRlThum=(RelativeLayout)itemView.findViewById(R.id.rl_thum);
        }

        public VideoViewHolder(View itemView) {
            super(itemView);
            initWidget(itemView);
        }
        public int getWidth() {
            int width = (ScreenUtils.getScreenW() - 6 * margin) / 3;
            return width;
        }


        public void checkPosition(int position) {
            //默认非第一行，非第一列
            if (position <= 2)
                isFirstLine = true;
            if (position % 3 == 0)
                isFristRow = true;
            else if (position % 3 == 1) {
                isSecondRow = true;
            } else if (position % 3 == 2) {
                isThridRow = true;
            }
        }

        public void resetMargin(int position) {
            int height = getWidth();
            int paddingtop = 0;
            int paddingbottom = 0;
            int paddingleft = 0;
            int paddingright = 0;
            if (isFirstLine) {
                paddingtop = 0;
                paddingbottom = 0;
            } else {
                paddingtop = 3 * margin;
                paddingbottom = 0;
            }
            if (isFristRow) {
                paddingleft = 0;
                paddingright = 2 * margin;
            } else if (isSecondRow) {
                paddingright = margin;
                paddingleft = margin;
            } else {
                paddingleft = 2 * margin;
                paddingright = 0;
            }
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(height, height);
            lp.setMargins(paddingleft, paddingtop, paddingright, paddingbottom);
            mRlThum.setLayoutParams(lp);

        }

        @Override
        public void renderView(final VideoCard data, int position) {
            checkPosition(position);
            resetMargin(position);
            mVideoThum.setImageUrl(data.video.thumUrl, HttpUtils.getImageLoader());
            mVideoDesc.setText(data.description);
            mZan.setText(data.videoAttach.praisenum + "");
            mAvatar.setImageUrl(data.user.avatar,HttpUtils.getAvatarImageLoader());
            this.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.videoCardClick(data);
                }
            });

        }

    }

}
